import router, { asyncRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getLoginTypeName, getLoginTypeRouter } from '@/utils/common'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login/property', '/login/government', '/login/public-security', '/test', '/auth-redirect', '/401', '/404'] // no redirect whitelist

// console.log('[permission]白名单', whiteList)

router.beforeEach(async(to, from, next) => {
  console.log('[router]路由跳转', to.path, from.path)
  // 开始进度条
  NProgress.start()
  // 设置网页标题
  document.title = getPageTitle(to.meta.title)
  // 确定用户是否已登录
  const hasToken = getToken()
  console.log('[router]token', hasToken)
  if (hasToken) {
    /* 有token */
    console.log('路径', to.path.indexOf('/login'))
    if (to.path.indexOf('/login') !== -1) {
      // 登录状态直接去首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 用户是否有用户信息和权限
      const hasRoles = !!store.getters.user_id && store.getters.permissions && store.getters.permissions.length > 0
      console.log('[router]是否有权限', hasRoles, store.state.user)
      if (hasRoles) {
        console.log('渲染页面')
        next()
      } else {
        try {
          console.log('[router]权限', asyncRoutes)
          // 获取用户信息
          const { permissions } = await store.dispatch('user/getInfo')
          console.log('[router]权限列表', permissions)

          // 根据角色生成可访问的路线图
          const accessRoutes = await store.dispatch('permission/generateRoutes', permissions)
          console.log('生成的路由', accessRoutes)
          // 动态添加可访问的路由
          router.addRoutes(accessRoutes)
          // 设置replace:true，这样导航就不会留下历史记录
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          console.log('权限发生错误', error)
          await store.dispatch('user/resetToken')
          Message.error(error || '发生错误')
          next(`/404`)
          NProgress.done()
        }
      }
    }
  } else {
    /* 没有token */
    // 展示去除白名单限制
    console.log('白名单', whiteList)
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      document.title = getLoginTypeName()
      next(getLoginTypeRouter())
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})
